/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-use-before-define */
import CustomerTable from "@/components/CustomerTable";
import DictTag from "@/components/DictTag";
import downLoad from "@/utils/download";
import { DeleteOutlined, ExclamationCircleFilled, PlusOutlined, TableOutlined } from "@ant-design/icons";
import { ActionType, PageContainer, ProColumns, ProTable } from "@ant-design/pro-components";
import { Button, Divider, FormInstance, Input, Modal, Tabs, Space, Typography, message, TabsProps } from "antd";
import React, { useEffect, useRef, useState } from "react";
import CardList from "./components/CardList";
import FileDetails from "./components/FileDetilas";
import UploadForm from "./components/UploadForm";
import { getDict } from "@/services/api/module/system/dict";
import { getPageList, remove, upload } from "@/services/api/module/tenant/storage/file";
import FilterDrawer from "@/components/FilterDrawer";
import { createTableColumns, pagination } from "./constants";
const { confirm } = Modal;
const OssFileList: React.FC = () => {
	const formTableRef = useRef<FormInstance>();
	const [formOpen, setFormOpen] = useState<boolean>(false);
	const actionRef = useRef<ActionType>();
	const [currentId, setCurrentId] = useState<number | undefined>(undefined);
	const [selectedRows, setSelectedRows] = useState<any>([]);
	const [detailOpen, setDetailOpen] = useState<boolean>(false);
	const [statusOptions, setStatusOptions] = useState<any>([]);
	const [dataSource, setDataSource] = useState<any>([]);
	const [fileTypeOptions, setFileTypeOptions] = useState<any>([]);
	const [showTab, setShowTab] = useState<string>("table");
	useEffect(() => {
		getDict("sys_normal_disable").then(data => {
			setStatusOptions(data);
		});
		getDict("sys_file_type").then(data => {
			console.log(data);
			setFileTypeOptions(data);
		});
	}, []);
	// 列定义
	const handleColumnRemove = (record: API.Setting.StorageFileVo) => {
		handleRemove(record?.id);
	};
	const handleColumnDownload = (record: API.Setting.StorageFileVo) => {
		handleDownload(record?.id);
	};
	const handleColumnDetails = (record: API.Setting.StorageFileVo) => {
		setDataSource(record);
		setCurrentId(record?.id);
		setDetailOpen(true);
	};
	const columns = createTableColumns(fileTypeOptions, handleColumnRemove, handleColumnDownload, handleColumnDetails);
	// 删除
	const handleRemove = async (ids: number | Array<number>) => {
		return new Promise((reslove, reject) => {
			remove(ids)
				.then((res: any) => {
					message.success(res.msg);
					if (actionRef.current) {
						actionRef.current.reload();
					}
					reslove(true);
				})
				.catch(() => {
					reject(true);
				});
		});
	};
	// 删除警告提示
	const showRemoveConfirm = (ids: any, names: any) => {
		confirm({
			title: "警告",
			icon: <ExclamationCircleFilled />,
			content: `确定删除文件名称为：${names} 的文件吗?`,
			onOk() {
				return handleRemove(ids);
			},
			onCancel() {}
		});
	};

	// 关闭表单刷新列表
	const handleTableForm = async () => {
		setFormOpen(false);
		setCurrentId(undefined);
		actionRef?.current?.reload();
	};
	// 上传文件
	const handleUploadFile = async (params: Array<any>) => {
		// console.log('params', );
		const formData = new FormData();
		// @ts-ignore
		for (let i = 0; i < params?.files?.length; i++) {
			// @ts-ignore
			formData.append("files", params?.files[i]?.originFileObj);
		}
		return new Promise((resolve, reject) => {
			upload(formData as any)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};

	const handleDownload = (ossId: number) => {
		downLoad.oss(ossId);
	};
	const [searchFormValue, setSearchFormValue] = useState<any>(undefined);
	const [searchValue, setSearchValue] = useState<any>(undefined);
	//数据请求
	const tableDataRequest = async (params: {} | undefined) => {
		return await getPageList({ ...searchFormValue, ...searchValue }).then((data: any) => {
			return data;
		});
	};
	const handleOnSearch = async (value: any) => {
		setSearchValue({
			userName: value
		});
		actionRef.current?.reload();
	};
	const items: TabsProps["items"] = [
		{
			key: "1",
			label: "Tab 1",
			children: "Content of Tab Pane 1"
		},
		{
			key: "2",
			label: "Tab 2",
			children: "Content of Tab Pane 2"
		},
		{
			key: "3",
			label: "Tab 3",
			children: "Content of Tab Pane 3"
		}
	];
	return (
		<>
			<CustomerTable<API.Setting.StorageFileVo>
				actionRef={actionRef}
				tableAlertRender={false}
				formRef={formTableRef}
				rowKey="id"
				toolbar={{
					search: (
						<Space>
							<Input.Search placeholder="配置键" allowClear style={{ width: 280 }} onSearch={handleOnSearch} />
							<FilterDrawer
								columns={columns}
								tableActionRef={actionRef}
								onReset={() => {
									setSearchFormValue(undefined);
									actionRef?.current?.reload();
								}}
								onSubmit={(values: any) => {
									setSearchFormValue(values);
									actionRef?.current?.reload();
								}}
							/>
						</Space>
					)
				}}
				search={false}
				pagination={pagination}
				request={tableDataRequest}
				// @ts-ignore
				toolBarRender={() => {
					return (
						<>
							<Button
								type="primary"
								key="upload"
								onClick={async () => {
									setFormOpen(true);
								}}
							>
								<PlusOutlined /> 上传文件
							</Button>
							{selectedRows?.length !== 0 && (
								<Button
									type="primary"
									key="remove"
									danger
									hidden={selectedRows?.length === 0}
									onClick={async () => {
										//todo 如果选中包含超级管理员也没办法显示，需要做
										showRemoveConfirm(
											Array.from(selectedRows, ({ id }) => id),
											Array.from(selectedRows, ({ originalName }) => originalName)
										);
									}}
								>
									<DeleteOutlined />
									批量删除
								</Button>
							)}
						</>
					);
				}}
				columns={columns}
				rowSelection={{
					onChange: (_, selectedRows) => {
						setSelectedRows(selectedRows);
					}
				}}
			/>
			<UploadForm
				open={formOpen}
				onCancel={() => {
					setFormOpen(false);
				}}
				onSubmit={async (files: Array<any>) => {
					return handleUploadFile(files);
				}}
			/>
			<FileDetails
				open={detailOpen}
				id={currentId}
				fileType={fileTypeOptions}
				dataSource={dataSource}
				onCancel={() => {
					setDetailOpen(false);
					setDataSource(undefined);
					setCurrentId(undefined);
				}}
			/>
		</>
	);
};

export default OssFileList;
